export default {
  namespaced: true,
  state: () => ({
    cart: JSON.parse(uni.getStorageSync("cart") || "[]")
    
  }),
  mutations: {
    getAddCart(state,goods){
      const findResult=state.cart.find(item=>item.goods_id===goods.goods_id)
           console.log(findResult)
      if(!findResult){
     state.cart.push(goods)
      }else{ 
        findResult.goods_count++
      }
       this.commit("m_cart/savatotle")
    },
   savatotle(state){
     uni.setStorageSync("cart",JSON.stringify(state.cart)) 
   },
   // 更新勾选状态
   updataSatae(state,goods){
     const findRes=state.cart.find(item=>item.goods_id===goods.goods_id)
     if(findRes){
       findRes.goods_state=goods.goods_state
        this.commit("m_cart/savatotle")
     } 
     },
     // 更新数量
        updataNumber(state,goods){
          const findRes=state.cart.find(item=>item.goods_id===goods.goods_id)
          if(findRes){
            findRes.goods_count=goods.goods_count
             this.commit("m_cart/savatotle")
             }
      },
      //删除商品
       deleteListItem(state,id){
         // 过滤当前的id和传过来的id,相等给新数组，不相等过滤
           state.cart=state.cart.filter(item=>item.goods_id!==id)
             this.commit("m_cart/savatotle")
       },
       // 全选和反选
        updataGenerations(state,newval){
             state.cart.forEach(item=>item.goods_state=newval)
               this.commit("m_cart/savatotle")
        }
  },   

 
  getters: {
    // 商品总数量
    total(state){
      // let c=0
      // state.cart.forEach(item=>c+=item.goods_count)
      //   return c
          return state.cart.reduce((c,item)=>c +=item.goods_count,0)
          
    },
    // 合计的总数量
    ckekedCont(state){
     return state.cart.filter(item=>item.goods_state).reduce((total,item)=>total +=item.goods_count,0)
    },
    // 全选
    radioCont(state){
      return state.cart.every(item=>item.goods_state)
    },
    // 反选
    unradioCont(state){
      return state.cart.some(item=>item.goods_state)
    },
    // 计算总价
    calculate(state){
     return state.cart.filter(item=>item.goods_state).reduce((total,item)=>total+=item.goods_count * item.goods_price,0).toFixed(2)
    }
  }
}
